import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# 定义高斯分布函数
def gaussian(x, a, b, c):
    return a * np.exp(-(x - b)**2 / (2 * c**2))

# 生成x值
x = np.linspace(0, 10, 100)

# 生成真实数据
a_true, b_true, c_true = 1, 5, 2
y_true = gaussian(x, a_true, b_true, c_true)

# 加入噪声
noise = np.random.normal(0, 0.5, size=x.shape)
y_noisy = y_true + noise

# 使用curve_fit进行拟合
popt, pcov = curve_fit(gaussian, x, y_noisy, p0=[1, 5, 2])

# 打印拟合参数
print(f"Fitted parameters: a = {popt[0]}, b = {popt[1]}, c = {popt[2]}")

# 绘制真实数据和拟合结果
plt.figure(figsize=(10, 6))
plt.plot(x, y_true, label='True Gaussian')
plt.scatter(x, y_noisy, label='Noisy Data', color='red', alpha=0.5)
plt.plot(x, gaussian(x, *popt), label='Fitted Gaussian', color='green')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Gaussian Fit')
plt.show()